package org.ssssssss.magicboot.interceptor;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.sun.javafx.collections.MappingChange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.MagicUser;
import org.ssssssss.magicapi.core.exception.MagicLoginException;
import org.ssssssss.magicapi.core.interceptor.AuthorizationInterceptor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


//@Component
public class CustomAuthorizationInterceptor  implements AuthorizationInterceptor {


    @Autowired
    private JdbcTemplate template;

    /**
     * 配置是否需要登录
     */
    @Override
    public boolean requireLogin() {
        return true;
    }

    /**
     * 根据Token获取User
     */
    @Override
    public MagicUser getUserByToken(String token) throws MagicLoginException {
        String id = (String)StpUtil.getLoginIdByToken(token);
        if (id == null) {
            throw new MagicLoginException("token无效");
        }
        String userName = StpUtil.getSession().getString("userName");
        return new MagicUser(id,userName,token);
    }

    @Override
    public MagicUser login(String username, String password) throws MagicLoginException {
        Map<String, Object > paramMap = new HashMap<>() ;
        paramMap.put("username", username) ;

        String sql = "select id,username,name,password,status from sys_user where is_del = 0 and is_login = 0 and username = ?";
        List<Map<String ,Object>> userList =  template.queryForList(sql, username) ;
        if(userList == null || userList.size() <1){
            throw new MagicLoginException("用户不存在");
        } else{
            String dbPassword = userList.get(0).get("password").toString();
            if(!SaSecureUtil.sha256(password).equals(dbPassword)){
                throw new MagicLoginException("密码输入错误");
            }
        }

        String id = userList.get(0).get("id").toString();
        //登录
        StpUtil.login(id);
        String token = StpUtil.getTokenValueByLoginId(id);
        String userName = userList.get(0).get("username").toString();

        StpUtil.getSession().set("userName",userName);
        return new MagicUser(id,userName,token);
    }

}
